package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.CaptchaYML;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    //验证码失效时间
    private final static long lateTime = 60_000;
    @Autowired
    private CaptchaYML captchaYML;
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaYML.getWidth(), captchaYML.getHeight());
        //存储验证码到session中
        session.setAttribute(captchaYML.getSession().getCode(), lineCaptcha.getCode());
        session.setAttribute(captchaYML.getSession().getDate(), System.currentTimeMillis());
        //设置响应
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        //输出到响应
        lineCaptcha.write(response.getOutputStream());
        //关闭输出流
        response.getOutputStream().close();
    }
    @RequestMapping("/check")
    public String checkCaptcha(String captchaCode, HttpSession session) {
        String savedCode = (String) session.getAttribute(captchaYML.getSession().getCode());
        long nowTime = System.currentTimeMillis();
        if(nowTime - (long)session.getAttribute(captchaYML.getSession().getDate()) > lateTime) {
            return "验证码已过期";
        }
        if(!StringUtils.hasLength(captchaCode) || !savedCode.equalsIgnoreCase(captchaCode)) {
            return "验证码错误";
        }
        return "";
    }
}
